<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CreateRoom 测试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .log { background: #f8f9fa; padding: 10px; margin: 10px 0; border-radius: 5px; white-space: pre-wrap; }
        .error { color: red; }
        .success { color: green; }
        .info { color: blue; }
        button { margin: 5px; padding: 10px; }
    </style>
</head>
<body>
    <h1>CreateRoom 功能测试</h1>
    
    <div>
        <label>用户名: <input type="text" id="userName" value="TestUser" /></label>
        <button onclick="joinUser()">加入系统</button>
    </div>
    
    <div>
        <label>房间名: <input type="text" id="roomName" value="TestRoom" /></label>
        <button onclick="createRoom()" id="createBtn" disabled>创建房间</button>
    </div>
    
    <div>
        <button onclick="testConnection()">测试连接状态</button>
        <button onclick="testMethod()">测试方法调用</button>
        <button onclick="testCreateRoomMethod()">测试创建房间方法</button>
        <button onclick="clearLog()">清空日志</button>
    </div>
    
    <div id="log" class="log"></div>

    <script src="https://unpkg.com/@microsoft/signalr@latest/dist/browser/signalr.min.js"></script>
    <script>
        let connection = null;
        let currentUserId = null;

        function log(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logDiv = document.getElementById('log');
            const logEntry = `[${timestamp}] ${message}\n`;
            logDiv.innerHTML += `<span class="${type}">${logEntry}</span>`;
            logDiv.scrollTop = logDiv.scrollHeight;
            console.log(`[${type.toUpperCase()}] ${message}`);
        }

        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }

        async function initConnection() {
            if (connection) return;

            try {
                connection = new signalR.HubConnectionBuilder()
                    .withUrl('/signaling')
                    .withAutomaticReconnect()
                    .build();

                // 注册事件
                connection.on('UserJoined', (data) => {
                    log(`收到 UserJoined: ${JSON.stringify(data)}`, 'success');
                    const userId = data.userId || data.UserId;
                    if (userId && !currentUserId) {
                        currentUserId = userId;
                        log(`用户ID已保存: ${currentUserId}`, 'success');
                        document.getElementById('createBtn').disabled = false;
                    }
                });

                connection.on('RoomCreated', (data) => {
                    // 兼容处理字段名称
                    const roomId = data.roomId || data.RoomId;
                    const roomName = data.roomName || data.RoomName;
                    log(`房间创建成功: ${JSON.stringify(data)}`, 'success');
                    log(`房间名称: ${roomName}, 房间ID: ${roomId}`, 'success');
                });

                connection.on('Error', (message) => {
                    log(`服务器错误: ${message}`, 'error');
                });

                connection.on('TestResponse', (message) => {
                    log(`测试响应: ${message}`, 'success');
                });

                connection.on('CreateRoomTestResponse', (message) => {
                    log(`创建房间测试响应: ${message}`, 'success');
                });

                connection.onclose((error) => {
                    log(`连接关闭: ${error ? error.message : '正常关闭'}`, 'error');
                    currentUserId = null;
                    document.getElementById('createBtn').disabled = true;
                });

                await connection.start();
                log('SignalR 连接成功', 'success');

            } catch (error) {
                log(`连接失败: ${error.message}`, 'error');
                throw error;
            }
        }

        async function joinUser() {
            try {
                if (!connection) {
                    await initConnection();
                }

                const userName = document.getElementById('userName').value.trim();
                if (!userName) {
                    log('请输入用户名', 'error');
                    return;
                }

                log(`开始加入系统: ${userName}`, 'info');
                await connection.invoke('JoinUser', userName);
                log('JoinUser 调用完成', 'info');

            } catch (error) {
                log(`加入系统失败: ${error.message}`, 'error');
            }
        }

        async function createRoom() {
            try {
                if (!connection || connection.state !== signalR.HubConnectionState.Connected) {
                    log('连接未建立或已断开', 'error');
                    return;
                }

                if (!currentUserId) {
                    log('用户未加入系统', 'error');
                    return;
                }

                const roomName = document.getElementById('roomName').value.trim();
                if (!roomName) {
                    log('请输入房间名', 'error');
                    return;
                }

                log(`开始创建房间: ${roomName}`, 'info');
                log(`当前用户ID: ${currentUserId}`, 'info');
                log(`连接状态: ${connection.state}`, 'info');

                // 修复：始终传递两个参数给 CreateRoom 方法
                log(`调用 CreateRoom 方法，参数: roomName="${roomName}", maxUsers=10`, 'info');
                await connection.invoke('CreateRoom', roomName, 10);
                log('CreateRoom 调用完成', 'success');

            } catch (error) {
                log(`创建房间失败: ${error.message}`, 'error');
                log(`错误详情: ${JSON.stringify(error)}`, 'error');
            }
        }

        function testConnection() {
            if (!connection) {
                log('连接未初始化', 'info');
                return;
            }

            log(`连接状态: ${connection.state}`, 'info');
            log(`连接ID: ${connection.connectionId || '未知'}`, 'info');
            log(`当前用户ID: ${currentUserId || '未设置'}`, 'info');
        }

        async function testMethod() {
            try {
                if (!connection || connection.state !== signalR.HubConnectionState.Connected) {
                    log('连接未建立或已断开', 'error');
                    return;
                }

                log('开始测试方法调用...', 'info');
                await connection.invoke('TestMethod', 'Hello from client');
                log('TestMethod 调用完成', 'success');

            } catch (error) {
                log(`测试方法调用失败: ${error.message}`, 'error');
                log(`错误详情: ${JSON.stringify(error)}`, 'error');
            }
        }

        async function testCreateRoomMethod() {
            try {
                if (!connection || connection.state !== signalR.HubConnectionState.Connected) {
                    log('连接未建立或已断开', 'error');
                    return;
                }

                const roomName = document.getElementById('roomName').value.trim() || 'TestRoom';
                log(`开始测试创建房间方法调用: ${roomName}`, 'info');
                await connection.invoke('CreateRoomTest', roomName);
                log('CreateRoomTest 调用完成', 'success');

            } catch (error) {
                log(`测试创建房间方法调用失败: ${error.message}`, 'error');
                log(`错误详情: ${JSON.stringify(error)}`, 'error');
            }
        }
    </script>
</body>
</html> 